#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time    : 2021/3/5 2:21 下午
# @Author  : 白辉东
# @Email   : xyxk-huidong.bai@ximalaya.com
# @File    : linuxLogCatchTools.py
# @Software: PyCharm

import threading
import logging.config
from public.common.speaker_type import SpeakerType
from public import rtosLogCatchTools

from config import projectPath
import subprocess


# 加载配置文件
logging.config.fileConfig(projectPath.LOG_CONFIG_DIR)
logger = logging.getLogger('my_logger')


def write_log(sn, speaker_type):
    """
    :param sn: 音箱设备sn
    :param speaker_type: 音箱种类
    :return:
    """
    if speaker_type == SpeakerType.NANO_RTOS:
        logger.info('开始抓取串口%s日志...' % sn)
        return rtosLogCatchTools.write_log(sn)

    # 清空adb logcat缓存
    subprocess.Popen('adb logcat -b all -c', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # 执行重定向日志脚本
    log_path = projectPath.LINUX_CASH_LOG_DIR
    command = _choice_shell(sn)
    try:
        sub = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        t = threading.currentThread()
        with open(log_path, 'a+', encoding='UTF-8') as fp:
            while getattr(t, "open", True):
                line = sub.stdout.readline().strip()
                # 编码转换，标准输出字节流转string
                log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
                if len(log):
                    fp.write(log + '\r')
        sub.kill()
    except Exception as e:
        logger.exception(e)
    logger.info('adb设备日志重定向成功!')


# 清除缓存日志
def clear_cash_log(speaker_type):
    if speaker_type == SpeakerType.NANO_RTOS:
        log_file_path = projectPath.RTOS_CASH_LOG_DIR
    else:
        log_file_path = projectPath.LINUX_CASH_LOG_DIR
    try:
        with open(log_file_path, 'r+', encoding='UTF-8') as f:
            f.truncate()
            logger.info('清除缓存日志成功...')
    except Exception as e:
        logger.error('清除缓存日志失败，请检查！')
        logger.exception(e)


# 可以兼容小美mini，小美带屏，小雅带屏，小雅Nano等linux系统设备
def _choice_shell(device_sn):
    shell = ''
    if 'XYBK' in device_sn:
        logger.info('小雅图书馆:%s日志抓取开始...' % device_sn)
        shell = 'adb -s ' + device_sn + ' logcat'

    elif any(key in device_sn for key in ['00001041', '00001021']):
        logger.info('小美mini:%s日志抓取开始...' % device_sn)
        shell = 'adb -s ' + device_sn + ' shell tail -F /userdata/OrionOSClientSDK.log'

    elif any(key in device_sn for key in ['NANO0', 'NANO000', 'NANO1']):
        logger.info('小雅Nano:%s日志抓取开始...' % device_sn)
        shell = 'adb -s ' + device_sn + ' shell tail -F /userdata/user.log'

    elif any(key in device_sn for key in ['00001031', '00001051']):
        logger.info('美的带屏:%s日志抓取开始...' % device_sn)
        shell = 'adb -s ' + device_sn + ' logcat'

    return shell
